<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>创建地图</title>
</head>
<script  src="./togeojson.js"></script>
<script src="./index.js"></script>
<script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&libraries=vector"></script>
<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>
<style type="text/css">
    html,
    body {
        height: 100%;
        margin: 0px;
        padding: 0px;
    }

    #container {
        width: 100%;
        height: 95%;
    }

    #download{
        position: absolute;
        right: 10px;
        bottom: 10px;
        z-index: 9999;
    }
</style>

<body onload="initMap()">  
    <div id="container"></div>
    <input type="button" id="download" onclick="downloadfile()" value="下载">    
    <!-- partial:index.partial.html -->
    <div class="mt-5">
        <div class="col-md-10 offset md-1">
        <input class="form-control" type="file" id="myGPX"/>
        </div>
    </div>
    <!-- partial -->      
    <script type="text/javascript">
        let markers = null;
        let outdata = null;
        function initMap() {
            var center = new TMap.LatLng(39.984104, 116.307503);
            //初始化地图
            map = new TMap.Map("container", {
                rotation: 20,//设置地图旋转角度
                pitch:30, //设置俯仰角度（0~45）
                zoom:12,//设置地图缩放级别
                center: center,//设置地图中心点坐标
                baseMap: {type:"satellite",features:["road","base"]}
            });
        }
        //移除marker事件
        function removeMarker() {
            if (markers) {
                markers.setMap(null);
                markers = null;
            }
        }        
        function downloadfile() {
            SaveAsFile(outdata,"./outpoint.csv","text/plain;charset=utf-8");
        }
        function SaveAsFile(t,f,m) {
            try {
                var b = new Blob([t],{type:m,
                    endings:"native"
                });
                saveAs(b, f);
            } catch (e) {
                window.open("data:"+m+"," + encodeURIComponent(t), '_blank','');
            }
        }
        //初始化
        let bounds = null;
        let markerGeometrys = null;
        
        //设置自适应显示marker
        function showMarker(){
            //判断标注点是否在范围内
            markerGeometrys.forEach(function(item){
                //若坐标点不在范围内，扩大bounds范围
                if(bounds.isEmpty() || !bounds.contains(item.position)){
                    bounds.extend(item.position);
                }
            })
            //设置地图可视范围
            map.fitBounds(bounds, {
                padding: 100 // 自适应边距
            });
        } 
        const myGPX = document.querySelector('#myGPX');
        myGPX.addEventListener('change', (e) => {
            const gpxFile = e.target.files
            if (!gpxFile.length) {
                return false;
            }
            const reader = new FileReader();
            reader.onload = (e) => {
                removeMarker();
                bounds = new TMap.LatLngBounds();
                outdata = "序号,纬度,经度\r\n";
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(e.target.result,"text/xml");
                console.log(toGeoJSON.gpx(xmlDoc));
                geojsondata = toGeoJSON.gpx(xmlDoc);
                

                // var b = new Blob([outdata],{type:"text/plain;charset=utf-8"});
                // saveAs(b, "outpoint.csv");
                let pointarray = new Array();
                let outdataarray = new Array();
                markerGeometrys = new Array();
                for(let _fdx = 0; _fdx < geojsondata.features.length; _fdx++) {
                    let _feature = geojsondata.features[_fdx];
                    if(_feature.geometry.type === 'LineString') {
                        continue;
                    }
                    markerGeometry = new Object();
                    if(_feature.properties.name === "起点") {
                        markerGeometry.styleId = 'start';
                    }else if(_feature.properties.name === "结束") {
                        markerGeometry.styleId = 'end';
                    }else {
                        markerGeometry.styleId = 'via';
                    }
                    let encrypt = coordtransform.wgs84togcj02(_feature.geometry.coordinates[0], _feature.geometry.coordinates[1]);
                    markerGeometry.position = new TMap.LatLng(encrypt[1],encrypt[0]);
                    markerGeometry.content = _feature.properties.name;
                    markerGeometrys.push(markerGeometry);   
                    outdata += _feature.properties.name + ',' + encrypt[0].toFixed(5) + ',' + encrypt[1].toFixed(5) + '\r\n';              
                }
                markers = new TMap.MultiMarker({
                        map: map, // 显示Marker图层的底图
                        styles: {
                            via: new TMap.MarkerStyle({
                            // 点标注的相关样式
                            width: 32, // 宽度
                            height: 32, // 高度
                            anchor: { x: 16, y: 16 }, // 标注点图片的锚点位置
                            src: './img/marker_via.png', // 标注点图片url或base64地址
                            color: '#333', // 标注点文本颜色
                            size: 16, // 标注点文本文字大小
                            direction: 'bottom', // 标注点文本文字相对于标注点图片的方位
                            offset: { x: 0, y: 0 }, // 标注点文本文字基于direction方位的偏移属性
                            strokeColor: '#fff', // 标注点文本描边颜色
                            strokeWidth: 1, // 标注点文本描边宽度
                            }),
                            start: new TMap.MarkerStyle({
                            width: 32,
                            height: 32,
                            anchor: { x: 16, y: 16 },
                            src: './img/marker_start.png',
                            color: '#333',
                            size: 22,
                            direction: 'bottom',
                            strokeColor: '#fff',
                            offset: { x: 0, y: 0 },
                            strokeWidth: 1,
                            }),
                            end: new TMap.MarkerStyle({
                            width: 32,
                            height: 32,
                            anchor: { x: 16, y: 16 },
                            src: './img/marker_end.png',
                            color: '#333',
                            size: 22,
                            direction: 'bottom',
                            strokeColor: '#fff',
                            offset: { x: 0, y: 0 },
                            strokeWidth: 1,
                            }),               
                        },
                        enableCollision: false, // 开启碰撞
                        geometries: markerGeometrys,
                });   
                showMarker();
            };
            result = reader.readAsText(gpxFile[0]);
        });           

    </script>
</body>

</html>